package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.dto.AdUserDto;
import com.heima.admin.mapper.AduserMapper;
import com.heima.admin.pojo.AdUser;
import com.heima.admin.service.AdminLoginService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminLoginServiceImpl extends ServiceImpl<AduserMapper, AdUser> implements AdminLoginService {

    @Override
    public ResponseResult login(AdUserDto userDto) {
        if (userDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"请输入用户名和密码");
        }

        if (StringUtils.isBlank(userDto.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"请输入用户名");
        }

        AdUser user = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, userDto.getName()));

        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
        }

        if (StringUtils.isBlank(userDto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "密码不能为空");
        }

        String salt = user.getSalt();
        String password = userDto.getPassword();
        password = DigestUtils.md5DigestAsHex((password + salt).getBytes());

        if (!password.equals(user.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码错误");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("token", AppJwtUtil.getToken(user.getId().longValue()));
        user.setPassword("");
        user.setSalt("");
        map.put("user", user);
        return ResponseResult.okResult(map);

    }
}
